import time
import shutil
from DrissionPage import Chromium
from loguru import logger
import pandas as pd
from read_search_file import get_search_comp, get_complete_sheet1, read_excel_with_images


def log_message(log_callback, message, color=None):
    if callable(log_callback):
        log_callback(message, color) if color else log_callback(message)
def create_creative_func(creative_view_tab, r_excel, browser, file_path, unit_next_button_ele=None, log_callback=None, df_sheet=None):
    img_col = 3 # 主图的图片在excel中的列位置
    output_folder = 'temp_images'
    ## 读取转化组件sheet
    df_search_comp, image_map = read_excel_with_images(file_path, output_folder=output_folder)
    creative_view_tab.wait.load_start()

    logger.info(f"进入创意界面")
    img_all_select = r_excel['封面全选']
    note_ids_arr = r_excel['笔记ID']
    indus_qualification = r_excel['行业资质']

    items = creative_view_tab.ele('css:.form-content > .group').eles('.item')

    for i, item in enumerate(items):
        item('tag:input@@class=d-text@@type=text@@placeholder=请输入你的创意名称').scroll.to_center()
        creative_name_ele = item('tag:input@@class=d-text@@type=text@@placeholder=请输入你的创意名称', timeout=15)
        # creative_view_tab.wait.eles_loaded('tag:input@@class=d-text@@type=text@@placeholder=请输入你的创意名称')  # 等待元素加载

        current_note_id = item('css:.d-table__body > tr > td:nth-child(2)').text # 当前笔记ID
        star_name = item('css:.d-table__body > tr > td:nth-child(4)').text # 当前达人昵称

        if current_note_id not in note_ids_arr:
            log_message(log_callback, f"当前笔记ID:{current_note_id}-达人昵称:{star_name}在转化组件中没有匹配值", "red")

        # 如果存在创意名称用自定义创意名称，否则默认达人昵称
        if '创意名称' in df_search_comp.columns:
            creative_name_handle(creative_name_ele, current_note_id, df_search_comp, star_name)
        else:
            creative_name_ele.input(star_name, clear=True)  # 填写创意名称

        # 投放资质
        # 第一个标签页编辑投放资质之后绑定至所有创意
        if i == 0:
            invest_qualification(creative_view_tab, indus_qualification, item)

        # 创意素材
        if img_all_select == '否':
            img_handle(creative_view_tab, item)

        # 自动优化
        if '自动优化' in df_sheet.columns:
            auto_optimize = r_excel['自动优化'] if pd.notna(r_excel['自动优化']) else "关闭"
            auto_optimize = auto_optimize.strip()
            item(f'tag:div@@class=flexible align-center@@text()={auto_optimize}').click(by_js=True)  # 自动优化
        else:
            item(f'tag:div@@class=flexible align-center@@text()=关闭').click(by_js=True)  # 自动优化

        ## 处理转化组件
        item(f'tag:span@@text()=转化组件').scroll.to_center()  # 滚到转化组件

        if item(f'tag:span@@text()=唤端组件', timeout=1):
            if not df_search_comp.empty:
                for s in df_search_comp.itertuples():
                    if current_note_id != s.笔记ID.strip():
                        continue
                    item(f'tag:span@@text()=唤端组件').scroll.to_center()
                    item(f'tag:span@@text()=唤端组件').parent(1).click(by_js=True)  # 点击唤端组件

                    # 处理引导文案
                    item('tag:span@@text()=引导文案').scroll.to_center()
                    lead_copy_writing = s.引导文案.strip()
                    lead_copy_write_handle(item, lead_copy_writing)

                    # 上传主图
                    current_row_index = s.Index
                    if (current_row_index, img_col) in image_map:
                        img_path = image_map[(current_row_index, img_col)]
                        logger.info(f'当前行:{current_row_index}, 图片路径:{img_path}')
                        item(f'.d-upload__picture').child().click.to_upload(f'{img_path}', by_js=True)
                        time.sleep(1)

                    # 兜底链接
                    if s.兜底链接:
                        backup_link = s.兜底链接.strip()
                        item('tag:input@@class=d-text@@placeholder=请输入未安装App时，打开的H5链接').run_js('this.value = arguments[0]; this.dispatchEvent(new Event("input"));', backup_link)
                        time.sleep(0.5)

                    # 主标题文案
                    if s.主标题:
                        main_title = s.主标题.strip()[:11]
                        item('tag:input@@class=d-text@@placeholder=请输入主标题文案').run_js('this.value = arguments[0]; this.dispatchEvent(new Event("input"));', main_title)
                        time.sleep(0.5)
                    break

    creative_view_tab.ele('css:.footer-action .d-button:nth-child(2)').click(by_js=True)  # 点击创意层级完成
    if not item('tag:span@@class=error@@text()^请填写主标题', timeout=1) and not item('tag:span@@class=error@@text()^请上传图片', timeout=1) and not item('tag:span@@class=error@@text()^请填写兜底链接', timeout=1):
        browser.close_tabs(creative_view_tab)
        logger.info(f"创意完成")


def lead_copy_write_handle(item, lead_copy_writing):
    # 先清空所有引导文案选项
    lead_item_lead_copy_writing = item('tag:span@@text()=引导文案').parent(1).next().child().eles('tag:div@@class=d-grid d-checkbox d-checkbox-main-label d-clickable')
    for lead_item in lead_item_lead_copy_writing:
        lead_item_class_str = lead_item.child().attr('class')
        if 'unchecked' not in lead_item_class_str:
            lead_item.run_js('this.click();')
    # 再根据选项依次选中
    copy_writing_arr = lead_copy_writing.split('\n')
    for w in copy_writing_arr:
        w = w.strip()
        if item(f'tag:input@@type=checkbox@@value={w}'):
            item(f'tag:input@@type=checkbox@@value={w}').parent(1).run_js('this.click();')


def img_handle(creative_view_tab, item):
    if item('tag:a@@text()=添加封面', timeout=2):
        item('tag:a@@text()=添加封面').scroll.to_center()
        item('tag:a@@text()=添加封面').click(by_js=True)
    if item('tag:a@@text()=选择封面', timeout=2):
        item('tag:a@@text()=选择封面').scroll.to_center()
        item('tag:a@@text()=选择封面').click(by_js=True)
    creative_view_tab.wait(1)
    img_all_select_eles = creative_view_tab.eles('css:.modal-content-right > .select-photo-item')
    if len(img_all_select_eles) > 1:
        # creative_view_tab.wait.eles_loaded('tag:span@@text()=全选')
        creative_view_tab.ele('tag:span@@text()=全选').click(by_js=True)
        time.sleep(1)
        creative_view_tab.ele('tag:span@@text()= 确认选择 ').click(by_js=True)
    else:
        creative_view_tab.ele('tag:span@@class$--size-text-paragraph d-text-nowrap d-text-ellipsis d-text-nowrap@@text()= 取消 ').click(by_js=True)


def invest_qualification(creative_view_tab, indus_qualification, item):
    item('tag:span@@class=link-text@@text()=编辑').wait(.5).click(by_js=True)
    if creative_view_tab.ele('tag:button@@text()=继续修改', timeout=2):
        logger.info("投放资质存在继续修改按钮")
        creative_view_tab.ele('tag:button@@text()=继续修改', timeout=2).click(by_js=True)
    # 选中行业资质具体内容
    if indus_qualification_content_ele := creative_view_tab.ele(f'tag:div@@class=d-grid d-option d-option-content --color-text-title@@text()={indus_qualification.strip()}', timeout=2):
        indus_qualification_content_ele.run_js('this.click()')  # 选中具体资质内容
    else:
        creative_view_tab.ele('css:.d-options-wrapper > .d-grid  > .d-grid-item:nth-child(1)', timeout=2).wait.displayed()
        creative_view_tab.ele('css:.d-options-wrapper > .d-grid  > .d-grid-item:nth-child(1)', timeout=2).run_js('this.click()')
    if all_bind_ele := creative_view_tab.ele('tag:span@@text()= 绑定至所有创意 ', timeout=2):  # 点击绑定当前创意
        all_bind_ele.parent(2).wait.enabled()
        all_bind_ele.parent(2).click(by_js=True)  # 点击绑定所有创意
    elif current_bind_ele := creative_view_tab.ele('tag:span@@text()= 绑定至当前创意 ', timeout=2):
        current_bind_ele.parent(2).wait.enabled()
        current_bind_ele.parent(2).click(by_js=True)  # 点击绑定当前创意
    else:
        creative_view_tab.ele('tag:span@@text()= 取消 ', timeout=2).click(by_js=True)
    if creative_view_tab.ele('tag:button@@text()=确认修改', timeout=2):
        logger.info("投放资质存在确认修改按钮")
        creative_view_tab.ele('tag:button@@text()=确认修改', timeout=2).click(by_js=True)


def creative_name_handle(creative_name_ele, current_note_id, df_search_comp, star_name):
    for d in df_search_comp.itertuples():
        if current_note_id != d.笔记ID.strip():
            continue
        excel_creative_name = d.创意名称

        if pd.notna(excel_creative_name):
            creative_name_ele.run_js('this.value = arguments[0]; this.dispatchEvent(new Event("input"));', excel_creative_name)  # 填写创意名称
            break
        else:
            creative_name_ele.input(star_name, clear=True)  # 填写创意名称
            break


def add_monitor_link_repeat(creative_view_tab, monitor_link, exposure_link):
    if add_monitor_link := creative_view_tab.ele('tag:div@@text()=添加监测链接', timeout=1.5):
        add_monitor_link.click(by_js=True, timeout=3)  # 点击添加监测链接
        creative_view_tab.wait(1)

        if pd.notna(monitor_link):
            monitor_link_arr = monitor_link.strip().split('\n')
            for monitor in monitor_link_arr:
                creative_view_tab.ele('tag:span@@text()=点击监测链接').next().ele('tag:span@@class=add-action@@text()= 添加 ').click(by_js=True, timeout=3)  # 点击添加
                creative_view_tab.ele('tag:div@@class=err-tips@@text()=请输入监测链接').wait.displayed()
                creative_view_tab.ele('tag:div@@class=err-tips@@text()=请输入监测链接').prev().ele('tag:input@@class=d-text@@placeholder=请输入链接').run_js('this.value = arguments[0]; this.dispatchEvent(new Event("input"));', monitor)  # 输入链接

        if pd.notna(exposure_link):
            exposure_link_arr = exposure_link.strip().split('\n')
            for exposure in exposure_link_arr:
                creative_view_tab.ele('tag:span@@text()=曝光监测链接').next().ele('tag:span@@class=add-action@@text()= 添加 ').click(by_js=True, timeout=3)  # 点击添加
                creative_view_tab.ele('tag:div@@class=err-tips@@text()=请输入监测链接').wait.displayed()
                creative_view_tab.ele('tag:div@@class=err-tips@@text()=请输入监测链接').prev().ele('tag:input@@class=d-text@@placeholder=请输入链接').run_js('this.value = arguments[0]; this.dispatchEvent(new Event("input"));', exposure)  # 输入链接

        creative_view_tab.ele('tag:span@@class$--size-text-paragraph d-text-nowrap d-text-ellipsis d-text-nowrap@@text()=保存').parent(2).click(by_js=True)  # 保存链接

if __name__ == '__main__':
    file_path = r"../shared/唤端-创建计划-样例.xlsx"

    browser = Chromium()  ## 临时测试、到时候删掉， 只保留调用create_unit()函数
    unit_view_tab = browser.latest_tab  ## 临时测试、到时候删掉
    unit_view_tab.get('https://ad.xiaohongshu.com/aurora/ad/create/creativity/121968939/270468569/16/1/1?isStep=true&from=CampaignList&AFormGrayFlag=false&vSellerId=67403ef0c2f45c001519af4b')  ## 临时测试、到时候删掉

    sheet1_data = get_complete_sheet1(file_path)
    for index, row in sheet1_data.iterrows():
        if index == 0:
            create_creative_func(unit_view_tab, row, browser, file_path, df_sheet=sheet1_data)
